package cn.eleven.dao.impl;

import cn.eleven.dao.LeaseDAO;
import cn.eleven.entity.Lease;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class LeaseDAOImpl implements LeaseDAO {

    /**
     * 根据房间ID查询当前有效的租赁信息（即end_time为null）
     */
    @Override
    public Lease findActiveLeaseByRoomId(Connection conn, int roomId) throws SQLException {
        String sql = "SELECT * FROM lease WHERE room_id = ? AND end_time IS NULL ORDER BY start_time DESC LIMIT 1";
        try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, roomId);  // 设置房间ID
            try (ResultSet rs = pstmt.executeQuery()) {
                if (rs.next()) {  // 如果查询结果有记录
                    return mapRowToLease(rs);  // 将查询结果映射为Lease对象
                }
            }
        }
        return null;
    }

    /**
     * 插入新的租赁记录，返回生成的租赁ID
     */
    @Override
    public int insert(Connection conn, Lease lease) throws SQLException {
        String sql = "INSERT INTO lease (user_id, room_id, start_time) VALUES (?, ?, ?)";
        try (PreparedStatement pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
            pstmt.setInt(1, lease.getUserId());
            pstmt.setInt(2, lease.getRoomId());
            pstmt.setTimestamp(3, new Timestamp(lease.getStartTime().getTime()));

            int affectedRows = pstmt.executeUpdate();  // 执行更新操作
            if (affectedRows == 0) {
                throw new SQLException("Creating lease failed, no rows affected.");
            }

            // 获取生成的租赁ID
            try (ResultSet generatedKeys = pstmt.getGeneratedKeys()) {
                if (generatedKeys.next()) {
                    return generatedKeys.getInt(1);  // 返回生成的租赁ID
                } else {
                    throw new SQLException("Creating lease failed, no ID obtained.");
                }
            }
        }
    }

    /**
     * 更新租赁记录，设置租赁结束时间
     */
    @Override
    public int update(Connection conn, Lease lease) throws SQLException {
        String sql = "UPDATE lease SET end_time = ? WHERE id = ?";
        try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setTimestamp(1, lease.getEndTime());
            pstmt.setInt(2, lease.getId());
            return pstmt.executeUpdate();  // 返回受影响的行数
        }
    }

    /**
     * 根据用户ID查询租赁记录
     */
    @Override
    public List<Lease> findByUserId(Connection conn, int userId) throws SQLException {
        String sql = "SELECT * FROM lease WHERE user_id = ?";
        try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, userId);  // 设置用户ID
            try (ResultSet rs = pstmt.executeQuery()) {
                List<Lease> leases = new ArrayList<>();
                while (rs.next()) {  // 遍历查询结果集
                    leases.add(mapRowToLease(rs));  // 将每行数据映射为Lease对象并添加到列表
                }
                return leases;
            }
        }
    }

    /**
     * 将查询结果的单行数据映射为Lease对象
     */
    private Lease mapRowToLease(ResultSet rs) throws SQLException {
        Lease lease = new Lease();
        lease.setId(rs.getInt("id"));
        lease.setUserId(rs.getInt("user_id"));
        lease.setRoomId(rs.getInt("room_id"));
        lease.setStartTime(rs.getTimestamp("start_time"));
        lease.setEndTime(rs.getTimestamp("end_time"));
        return lease;
    }

    /**
     * 根据房间ID和用户ID查询当前有效的租赁记录
     */
    @Override
    public Lease findActiveLeaseByRoomAndUser(Connection conn, int roomId, int userId) throws SQLException {
        String sql = "SELECT * FROM lease WHERE room_id = ? AND user_id = ? AND end_time IS NULL";
        try (PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setInt(1, roomId);
            ps.setInt(2, userId);
            try (ResultSet rs = ps.executeQuery()) {
                if (rs.next()) {
                    Lease lease = new Lease();
                    lease.setId(rs.getInt("id"));
                    lease.setRoomId(rs.getInt("room_id"));
                    lease.setUserId(rs.getInt("user_id"));
                    lease.setStartTime(rs.getTimestamp("start_time"));
                    lease.setEndTime(rs.getTimestamp("end_time"));
                    return lease;
                }
            }
        }
        return null;
    }
}
